//
//  CZUserAccountViewModel.swift
//  WeiBoNew
//
//  Created by 秦川 on 16/5/12.
//  Copyright © 2016年 秦川. All rights reserved.
//

import UIKit

class CZUserAccountViewModel: NSObject {
    static let shareUserAccount: CZUserAccountViewModel = CZUserAccountViewModel()
    
    override init() {
        super.init()
        userAccount = CZUserAcount.loadUserAccount()
    }
    var islogin: Bool{
    
    return accessToken != nil
    
    }
    var accessToken: String?{
        guard let token = userAccount?.access_token else{
        return nil
        }
     let result = userAccount?.expiresDate?.compare(NSDate())
        if result == NSComparisonResult.OrderedDescending{
        return token
        }else{
        return nil
        }
    }
    var userAccount : CZUserAcount?
    
    // 通过code  获取accesstoken
     func requestAccessToken(code: String,complete: (isSuccess: Bool)->()){
        CZNetWorkTools.shareTools.requestAccessToken(code) { (response, error) -> () in
            if error != nil {
                complete(isSuccess: false)
                return
            }
            guard let dict = response as? [String: AnyObject] else{
                complete(isSuccess: false)

                print("数据不是一个正确的json格式")
                return
            }
            let userAccount = CZUserAcount(dict: dict)
            print(userAccount)
            self.requestUserInfo(userAccount,complete: complete)
            
            
        }
    }
    //  获取用户信息
    func requestUserInfo(userAccount: CZUserAcount,complete: (isSuccess: Bool)->()){
        
        CZNetWorkTools.shareTools.requestUserInfo(userAccount) { (response, error) -> () in
            if error != nil {
                complete(isSuccess: false)

                return
            }
            guard let dict = response as? [String: AnyObject] else{
                complete(isSuccess: false)

                print("数据不是一个正确的json格式")
                return
            }
            userAccount.name = dict["name"] as? String
            userAccount.avatar_large = dict["avatar_large"] as? String
           let result = userAccount.saveUserAccount()
            print(userAccount)
            self.userAccount = userAccount
            if result{
            complete(isSuccess: true)
            }else{
            complete(isSuccess: false)
            }
        }
    }
    
    
    
    
    
    
    
}
